﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;

namespace FlaresAtHand
{
    public static class Logger
    {
        private static string filename = "Log.txt";
        private static string _datafile = null;

        private static Dictionary<DateTime, String> _messages = new Dictionary<DateTime, String>();

        private static void EnsureFileExists()
        {
            if (_datafile == null)
            {
                //Happens when starting the program
                _datafile = Utils.GetDataFilePath(filename);
                File.Delete(_datafile); // Erase old logs
                _datafile = Utils.SetUpDataFile(filename);
            }
        }

        public static void Log(String message)
        {
            EnsureFileExists();
            try
            {
                _messages.Add(DateTime.Now, message);
            }
            catch
            {
            }
        }

        private static Timer _flushTimer = new Timer(new TimerCallback(TimerFired), null, 5000, 15000);

        private static void TimerFired(Object state)
        {
            if(_messages.Count > 0){
                Flush();
            }
        }

        public static void Flush()
        {
            using (var writer = File.AppendText(_datafile))
            {
                writer.AutoFlush = false;
                foreach (var pair in _messages.OrderBy(x => x.Key))
                {
                    writer.WriteLine(String.Format("[{0}]{1}", pair.Key, pair.Value));
                }
            }
            _messages.Clear();
        }
    }
}
